function [ label ] = getlabel( distances )
    % determines the best label given a set of labels & distances
    % input: an Nx2 array of (label,distance) pairs
    % output: the label of the best (label,distance) pair
    
    mins = zeros(10,2);
    mins(1:10,1) = 0:9;
    
    for i=1:size(distances,1)
        mins(distances(i,1) + 1, 2) = mins(distances(i,1) + 1, 2) + 1;
    end
    mins = sortrows(mins,2);
    
    label = mins(10,1);
    
%     % pick random
%     
%     RandStream.setDefaultStream ... 
%      (RandStream('mt19937ar','seed',sum(100*clock)));
%        
%     i = 9;
%     same = 1;
%     while(i >= 1)
%         if(mins(10,2) == mins(i,2))
%             same = same + 1;
%         end
%         i = i - 1;
%     end
%     r = randi(same) - 1;
%     label = mins(10-r,1);
    
    % pick nearest
    if(mins(10,2) == mins(9,2))
        j=1;
        while(distances(j,1) ~= mins(10,1))
            j = j+1;
        end
        nearest = distances(j,2);

        ind = 9;
        while(mins(ind,2) == max(mins,2))
            j=1;
            while(distances(j,1) ~= mins(ind,1))
                j = j+1;
            end
            if(distances(j,2) < nearest)
                label = mins(ind,1);
                nearest = distances(j,2);
            end
            ind = ind - 1;
        end
    end
    
end